package com.yj.suncity.activity.shouye;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.pay.demo.Result;
import com.alipay.sdk.pay.demo.SignUtils;
import com.yj.suncity.R;
import com.yj.suncity.activity.shouye.bean.ShouyeListBean;
import com.yj.suncity.activity.shouye.bean.UploadPayBean;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.publish.PublishProductActivity;
import com.yj.suncity.utis.HttpUtil;
import com.yj.suncity.utis.ProgressUtil;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.viewpager.VerticalViewPagerScroll;
import com.yj.suncity.viewpager.ViewPagerScrollShouye;

public class MyZhanghuActivity extends Activity implements OnClickListener{
	private static final int FAIL = 1;
	private static final int SUCCESS = 2;
	private static final int IO_EXCEPTION = 3;
	private static final int JSON_EXCEPTION = 4;
	private Context context;
	private String userId;
	private boolean isShop;
	private List<NameValuePair> pairs = new ArrayList<NameValuePair>();

	private ImageView mImg_1, mImg_2;
	private TextView mTxt_1, mTxt_2, mTxt_edt_1, mTxt_edt_2;
	private EditText mEdt_txt_1, mEdt_txt_2;
	private Button mBtn_duihuan;
	public static final String PARTNER = "2088811449196531";
	public static final String SELLER = "yangguangtongcheng@163.com";
	public static final String RSA_PRIVATE = "MIICXAIBAAKBgQCreu0iowo5RkqszD2enu+UPnYtSwwMA/rz5ONLH0HhLJIEqmEjBC2j6jR/KwrwRdb9xtShVXrkDCwqvx0K+ANf5NCAndNr4CmgPPGd0ptUNXstWXWO0ojJ6gqsJJXASV3tZApjQn/eg49bB4UiKZrJFvZwBxw6JHvE5cxsO7bi+QIDAQABAoGAXKmCdtMPdT+sno+HRK2x3LOb/IGvMtb7xsuKn092tAz3opnG/7sERq0KTSWfNZMnx96ni767N3v0aez37rNybn5jSsqluGLf9UFzXFAxYJkGI4I/OZbvAluFwJjtT/knCTj6MUHLEtJllosGJNAp1Nzqk2vIDNNFlxbSSENpIOECQQDcmeIscxItMzsQB2+M0dnw1iPD8nThMRUSACYpv0wVSrltz0JICfJ5IuZ6t0qPhsZQ5akM0U2waEiarev5ifmtAkEAxv8xzyiqtwXG8RW+OtDjfMN7MFF/pojs0do793hBpFhZzBOzjJhiaJjkGaFUG69+lTP6nhYP+wUcsnOtVuIP/QJBAKe+c9ds4MNyE1VK8i3YXKrfim6zbODX27fGWT6hcg82tO2lDjeNKM2oFi32NkIRL7fQCs3uUe70PVExMyCbJDkCQFhsUvSrLFhRL9o2gCXgZgUtU5Lf0+nrE9gXsee/vuNJAvXEl1bU631w2oJtBlObApNH2ofeY9F1rw+4iQB/SP0CQEOdtt+sXvCmEKqvksj0wy3HkflvsstZEUZSoBLy2NAOKysScDUr7GQyRNwH2U0TfEnKsvnDI+AiOjjZgbah1YY=";
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;

	private ProgressUtil progressUtil;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				progressUtil.ShowProgress(context, false, false, "正在提交......");
				ToastUtil.ShowToast(context, ""+(String)msg.obj);
				break;
			case SUCCESS:
				progressUtil.ShowProgress(context, false, false, "正在提交......");
				try {
					JSONObject jsonObject = new JSONObject(""+(String)msg.obj);
					UploadPayBean infoBean = new UploadPayBean(jsonObject);
					if (infoBean.getSuccess().equals("1")) {
						pay(mEdt_txt_1.getText().toString(), infoBean.getOrderNum(), infoBean.getUrl());
					}else{
						ToastUtil.ShowToast(context, infoBean.getMsg());
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case IO_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在提交......");
				ToastUtil.ShowToast(context, "网络异常！");
				break;
			case JSON_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在提交......");
				ToastUtil.ShowToast(context, "数据解析异常！");
				break;
			default:
				break;
			}
		};
	};
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				Result resultObj = new Result((String) msg.obj);
				String resultStatus = resultObj.resultStatus;

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					ToastUtil.ShowToast(context, "支付成功");
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000” 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						ToastUtil.ShowToast(context, "支付结果确认中");
						

					} else {
						ToastUtil.ShowToast(context, "支付失败");

					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				ToastUtil.ShowToast(context, "检查结果为：" + msg.obj);
				break;
			}
			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_zhanghu);
		context = this;
		userId = getIntent().getStringExtra("userid");
		isShop = getIntent().getBooleanExtra("isshop", false);
		findView();
	}
	private void findView() {
		mBtn_duihuan=(Button) findViewById(R.id.btn_duihuan);
		mBtn_duihuan.setOnClickListener(this);
		mImg_1 = (ImageView) findViewById(R.id.img_1);
		mImg_2 = (ImageView) findViewById(R.id.img_2);
		mTxt_1 = (TextView) findViewById(R.id.txt_1);
		mTxt_2 = (TextView) findViewById(R.id.txt_2);
		mTxt_edt_1 = (TextView) findViewById(R.id.txt_edt_1);
		mTxt_edt_2 = (TextView) findViewById(R.id.txt_edt_2);
		mEdt_txt_1 = (EditText) findViewById(R.id.edt_txt_1);
		mEdt_txt_2 = (EditText) findViewById(R.id.edt_txt_2);
		if (isShop) {
			((TextView) findViewById(R.id.txt_title_name)).setText("现金充值");
			mImg_1.setImageResource(R.drawable.rmb_icon);
			mImg_2.setImageResource(R.drawable.yinyuan_golds);
			mBtn_duihuan.setText("充值");
			mTxt_1.setText("1人民币");
			mTxt_2.setText("1元");
			mTxt_edt_1.setText("现金总数");
			mTxt_edt_2.setText("人民币数");
			mEdt_txt_1.setHint("请输入您要充值的现金总数");
			mEdt_txt_2.setHint("需要人民币数");
		} else {
			((TextView) findViewById(R.id.txt_title_name)).setText("现金提现");
			mImg_2.setImageResource(R.drawable.rmb_icon);
			mImg_1.setImageResource(R.drawable.yinyuan_golds);
			mBtn_duihuan.setText("提现");
			mTxt_2.setText("1人民币");
			mTxt_1.setText("1元");
			mTxt_edt_1.setText("人民币数");
			mTxt_edt_2.setText("现金总数");
			mEdt_txt_1.setHint("请输入您要提现的人民币数");
			mEdt_txt_2.setHint("需要现金总数");
		}
		mEdt_txt_1.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				mEdt_txt_2.setText(s);
			}
		});

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.btn_jisuan:
			String sAllTotle = mEdt_txt_1.getText().toString().trim();
			if (sAllTotle.equals("")) {
				ToastUtil.ShowToast(context, "请输入要兑换总数！");
				return;
			}

			mEdt_txt_2.setText(sAllTotle);
			break;
		case R.id.btn_duihuan://充值、提现
			if (isShop) {				
				uploadPay();
			}
			break;
		default:
			break;
		}

	}
	private void uploadPay() {
		progressUtil = new ProgressUtil();
		progressUtil.ShowProgress(context, true, false, "正在提交......");
		pairs.clear();
		final String path = URLCon.用户;
		pairs.add(new BasicNameValuePair("action", "alipay_pay"));
		pairs.add(new BasicNameValuePair("userid", userId));
		pairs.add(new BasicNameValuePair("amount", mEdt_txt_1.getText().toString()));
		pairs.add(new BasicNameValuePair("silver", mEdt_txt_2.getText().toString()));

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String json = HttpUtil.HttpClientdoPost(path, pairs);
					if(json != null && !"".equals(json)){						
						JSONObject jsonObject = new JSONObject(json);
						Message message = new Message();
						if (jsonObject.optString("success").equals("1")) {
							message.what = SUCCESS;
							message.obj = json;
						} else {
							message.what = FAIL;
							message.obj = jsonObject.optString("msg");
						}
						handler.sendMessage(message);
					}else{
						Message message = new Message();
						message.what = JSON_EXCEPTION;
						handler.sendMessage(message);
					}

				} catch (IOException e) {
					Message message = new Message();
					message.what = IO_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (JSONException e) {
					Message message = new Message();
					message.what = JSON_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				}
			}
		});
		thread.start();
		thread = null;
//		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
//				false, null, true, "正在提交......", new ResultCallBack() {
//					@Override
//					public void JSONResult(JSONObject jsonObject) {
//						UploadPayBean infoBean = new UploadPayBean(jsonObject);
//						if (infoBean.getSuccess().equals("1")) {
//							pay("", infoBean.getOrderNum(), infoBean.getUrl());
//						}else{
//							ToastUtil.ShowToast(context, infoBean.getMsg());
//						}
//					}
//				});
//		asyncTaskUtil.execute(path);
	}
	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(String price,String orderNumber,String url) {
		String orderInfo = getOrderInfo("充值", "现金充值", price,orderNumber,url);
		String sign = sign(orderInfo);
		try {
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(MyZhanghuActivity.this);
				// 调用支付接口
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				PayTask payTask = new PayTask(MyZhanghuActivity.this);
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, String price,String orderNum,String url) {
		// 合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + orderNum + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + url
				+ "\"";

		// 接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 获取外部订单号
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}
}
